package com.cppsu.cgx.libraryseatselection.services.impl;

import com.cppsu.cgx.libraryseatselection.common.utils.JwtTokenUtil;
import com.cppsu.cgx.libraryseatselection.dto.AdminParam;
import com.cppsu.cgx.libraryseatselection.entity.Admin;
import com.cppsu.cgx.libraryseatselection.mapper.AdminMapper;
import com.cppsu.cgx.libraryseatselection.services.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author: guibo
 * @Description:
 * @Date: Created in 9:16 2021/3/12
 * @Modified By:
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Override
    public String login(AdminParam adminParam) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(adminParam.getUsername());
            if (!passwordEncoder.matches(adminParam.getPassword(), userDetails.getPassword())||adminParam.getPassword().equals(userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException ignored) {

        }
        return token;
    }

    @Override
    public int add(AdminParam adminParam) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminParam,admin);
        return adminMapper.insert(admin);
    }

    @Override
    public int update(AdminParam adminParam) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminParam,admin);
        return adminMapper.updateByPrimaryKeySelective(admin);
    }
}
